//  配置基地址
import store from '../store' //通过vuex获取token
const baseURl = 'https://1201xixie.ciyuantiaoyue.com/api/' //  本地服务器  线上
function apiRequest(
	method,
	url = '',
	data = {},
	isAuth = true,
	isAutha = false
) {
	let header = {}
	if (isAuth) {
		header = {
			// 'Authorization': store.state.token ? store.state.token : ''
			'token': store.state.token ? store.state.token : ''
		}
	}
	if (isAutha) {
		header = {
			// 'Authorization': store.state.token ? store.state.token : ''
			'token': store.state.tokena ? store.state.tokena : ''
		}
	}
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
		uni.request({
			url: baseURl + url,
			method: method,
			data: data,
			header: header,
			timeout: 5000,
			//  成功回调
			success: res => {
				resolve(res.data)
				if (res.data.code == 401) {
					uni.showModal({
						title: '',
						content: '请重新登录',
						success: function(res) {
							if (res.confirm) {
								// console.log('用户点击确定');
								store.commit('logout')
								uni.navigateTo({
									url: '/pages/share/login/login'
								})
							} else if (res.cancel) {
								uni.navigateBack()
								// console.log('用户点击取消');
							}
						}
					})
				}
				uni.hideLoading()
			},
			//  错误回调
			fail: err => {
				uni.hideLoading()
				uni.showToast({
					title: '服务器出错！',
					icon: 'error',
					duration: 2000
				})
				reject(err)

				console.log('cuowy');
			},
			//  请求完成回调
			complete: () => {
				uni.hideLoading()
			}
		});
	})
}
const request = {
	/**
	 * @param {String}  url     -请求url
	 * @param {Object}  data    -请求数据
	 * @param {Boolean} isAuth  -是否需要token 默认需要
	 * @param {Boolean} isAutha  -是否需要临时tokena 默认不需要
	 **/
	get(url, data, isAuth, isAutha) {
		return apiRequest('GET', url, data, isAuth, isAutha);
	},
	post(url, data, isAuth, isAutha) {
		return apiRequest('POST', url, data, isAuth, isAutha);
	},
	upload(url, data, isAuth, isAutha) {
		return apiRequest('upload', url, data, isAuth, isAutha);
	},
	put(url, data, isAuth, isAutha) {

		return apiRequest('put', url, data, isAuth, isAutha);
	},
	delete(url, data, isAuth, isAutha) {
		return apiRequest('delete', url, data, isAuth, isAutha);
	}
}
export default request
